package com.zzh.jetpackdemo.paging

import androidx.paging.PageKeyedDataSource

/**
 * @author zhangzhihao
 * @email zhangzhihao@gongjiangren.net
 * @date 2020-11-25
 * @desc
 */
class CalendarDataSource : PageKeyedDataSource<Int, Int>() {
    override fun loadInitial(
        params: LoadInitialParams<Int>,
        callback: LoadInitialCallback<Int, Int>
    ) {
        val data: MutableList<Int> = ArrayList()
        for (i in 0..41) {
            data.add(i)
        }
        callback.onResult(data, 0, 42, 0, 42)
    }

    override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, Int>) {
        val afterDate = params.key
        var list = afterData(afterDate)
        callback.onResult(list, list[list.size - 1])
    }

    override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, Int>) {
        val beforeDate = params.key
        var list = beforeData(beforeDate)
        callback.onResult(list, list[0])
    }

    private fun beforeData(startNum: Int): List<Int> {
        val data = arrayListOf<Int>()
        val start = startNum - 42
        for (i in start until startNum) {
            data.add(i)
        }
        return data
    }

    private fun afterData(startNum: Int): List<Int> {
        val data = arrayListOf<Int>()
        val endNum = startNum + 42;
        for (i in startNum until endNum) {
            data.add(i)
        }
        return data
    }


}